package com.kingint.web.admin.serve.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kingint.mbg.bas.entity.BasDepartment;
import com.kingint.mbg.dto.BackQueryParam;
import com.kingint.mbg.dto.MemberReturn;
import com.kingint.mbg.ser.entity.SerMessageReplyMiddle;
import com.kingint.mbg.ser.entity.SerSendMessage;
import com.kingint.mbg.ser.entity.SerWorkOrder;
import com.kingint.mbg.ser.mapper.SerMessageReplyMiddleMapper;
import com.kingint.mbg.ser.mapper.SerSendMessageMapper;
import com.kingint.mbg.ser.mapper.SerWorkOrderMapper;
import com.kingint.mbg.sys.entity.UmsMember;
import com.kingint.mbg.sys.mapper.UmsMemberMapper;
import com.kingint.web.admin.serve.service.SerSendMessageService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kingint.web.portal.base.service.DepartmentService;
import com.kingint.web.portal.serve.service.ActivitiCancelService;
import com.kingint.web.sys.service.UmsAdminService;
import com.kingint.web.util.CharUtil;
import com.kingint.web.util.WorkType;
import com.kingint.web.util.WorkTypeUtil;
import com.kingint.web.vo.MessageBean;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 群发通知表 服务实现类
 * </p>
 *
 * @author wxh
 * @since 2020-12-25
 */
@Service
@Slf4j
public class SerSendMessageServiceImpl extends ServiceImpl<SerSendMessageMapper, SerSendMessage> implements SerSendMessageService {

    @Resource
    private SerSendMessageMapper sendMessageMapper;
    @Resource
    private SerWorkOrderMapper workOrderMapper;
    @Resource
    private UmsAdminService adminService;
    @Resource
    private UmsMemberMapper memberMapper;
    @Resource
    private MessageBean messageBean;
    @Resource
    private TaskService taskService;
    @Resource
    private DepartmentService departmentService;
    @Resource
    private SerMessageReplyMiddleMapper messageReplyMiddleMapper;
    @Resource
    private ActivitiCancelService activitiCancelService;

    @Override
    public Integer deleteSendMessage(Integer workId) {
        SerWorkOrder serWorkOrder = new SerWorkOrder();
        serWorkOrder.setId(workId);
        serWorkOrder.setStatus(1);
        int i = workOrderMapper.updateById(serWorkOrder);
        return i;
    }

    @Override
    public IPage<SerSendMessage> getSendMessageList(BackQueryParam queryParam, Integer pageNum, Integer pageSize) {
        UmsMember currentMember = adminService.getCurrentMember();
        Integer hotelId = currentMember.getHotelId();
        if (StringUtils.isEmpty(hotelId)) {
            log.debug("该账号没有关联对应酒店id");
            return null;
        }
        queryParam.setHotelId(hotelId);
        IPage<SerSendMessage> page = new Page<>(pageNum, pageSize);
        IPage<SerSendMessage> sendMessageList = sendMessageMapper.getSendMessageList(page, queryParam);
        List<SerSendMessage> records = sendMessageList.getRecords();
        if (!CollectionUtils.isEmpty(records)) {
            for (SerSendMessage info : records) {
                Integer workId = info.getWorkId();
                SerWorkOrder serWorkOrder = workOrderMapper.selectById(workId);
                Long submitUserId = serWorkOrder.getSubmitUserId();
                if(!StringUtils.isEmpty(submitUserId)){
                    UmsMember umsMember = memberMapper.selectById(submitUserId);
                    info.setSubmitUserName(umsMember.getUsername());
                }
            }
        }
        return sendMessageList;
    }

    @Override
    public Integer updateInfo(SerSendMessage serSendMessage) {
        int i = sendMessageMapper.updateById(serSendMessage);
        return i;
    }

    @Override
    public int insertSendMessageInfo(SerSendMessage serSendMessage) {
        UmsMember currentMember = adminService.getCurrentMember();
        Integer hotelId = currentMember.getHotelId();
        if (StringUtils.isEmpty(hotelId)) {
            log.debug("该账号没有关联酒店id");
            return 0;
        }
        //进行相关的处理
        SerWorkOrder workOrder = new SerWorkOrder();
        workOrder.setHotelId(hotelId);//对应酒店
        workOrder.setSubmitUserId(currentMember.getId());//提交人员
        workOrder.setOrderSn(CharUtil.generateOrderSn());//工单号
        //查询工单类型
        Integer typeId = WorkTypeUtil.getWorkTypeIdByName(WorkType.sendMessageName);
        workOrder.setWorkTypeId(typeId);
        workOrder.setCreateTime(new Date());//创建时间
        //插入总工单中
        int insert = workOrderMapper.insert(workOrder);

        //插入群发通知工单中
        serSendMessage.setCreateTime(new Date());
        serSendMessage.setWorkId(workOrder.getId());
        sendMessageMapper.insert(serSendMessage);

        //查询相关人员，添加回复人员中间表
        //0,部门全选，1，对应部门下人全选，2.对应部门下的某些人
        Integer sendTyp = serSendMessage.getSendTyp();
        if (sendTyp == 0) {//查询对应酒店下的所有部门信息
            List<BasDepartment> list = departmentService.getDepartmentListByHotelId(hotelId);
            if (!CollectionUtils.isEmpty(list)) {
                List<Integer> collect = list.stream().map(BasDepartment::getId).collect(Collectors.toList());
                handleSelectDepartment(collect, workOrder.getId());
            }
        } else if (sendTyp == 1) {//选择多个部门
            List<Integer> departIdList = serSendMessage.getDepartIdList();
            if (!CollectionUtils.isEmpty(departIdList)) {
                handleSelectDepartment(departIdList, workOrder.getId());
            }
        }else if(sendTyp==2){
            List<Long> idList = serSendMessage.getMemberUserIdList();
            if(!CollectionUtils.isEmpty(idList)){
                handleUserList(idList,workOrder.getId());
            }
        }
        String businessKey = messageBean.getProcessInstanceKey() + "_" + currentMember.getHotelId() + "_" + workOrder.getId();//业务相关参数

        //启动相关流程
        HashMap<String, Object> map = new HashMap<>();
        map.put(messageBean.getCreateNameEl(), currentMember.getUsername());
        String processInstanceId = activitiCancelService.startProcess(messageBean.getProcessInstanceKey(), businessKey, map);
        workOrder.setProcessInstanceId(processInstanceId);
        workOrder.setOrderStatus(5);
        workOrderMapper.updateById(workOrder);
        //完成相关的任务

        Task task = taskService.createTaskQuery()
                .processInstanceId(processInstanceId)
                .singleResult();
        taskService.complete(task.getId());
        return insert;
    }

    private void handleUserList(List<Long> idList, Integer id) {
        idList.stream().forEach(s->{
            SerMessageReplyMiddle middle = new SerMessageReplyMiddle();
            middle.setCreateTime(new Date());
            middle.setReceiveUserId(s);
            middle.setSendMessageId(id);
            middle.setIsRead(0);//未读
            messageReplyMiddleMapper.insert(middle);
        });
    }
    /**
     * 处理选择的部门
     *
     * @param departmentList
     * @param id
     */
    private void handleSelectDepartment(List<Integer> departmentList, Integer id) {
        //查询每个部门下的人
        QueryWrapper<UmsMember> wrapper = new QueryWrapper<>();
        wrapper.in("department_id", departmentList);
        List<UmsMember> umsMembers = memberMapper.selectList(wrapper);
        if (umsMembers.size() != 0) {
            List<Long> collect1 = umsMembers.stream().map(UmsMember::getId).collect(Collectors.toList());
            //插入相关的信息
            collect1.stream().forEach(s -> {
                SerMessageReplyMiddle middle = new SerMessageReplyMiddle();
                middle.setCreateTime(new Date());
                middle.setReceiveUserId(s);
                middle.setSendMessageId(id);
                middle.setIsRead(0);//未读
                messageReplyMiddleMapper.insert(middle);
            });
        }
    }
}
